import { useEffect } from "react";
import { useHistory, useParams } from "react-router-dom";
import navsApi from "../../api/navs";
import { Card, Form, Breadcrumb, Space, Button, Input, message } from "antd";
const layout = {
  labelCol: {
    span: 10,
  },
  wrapperCol: {
    span: 14,
  },
};
const validateMessages = {
  required: "必填项不能为空！",
  types: {
    number: "请输入有效的数字!",
  },
};
// eslint-disable-next-line
export default () => {
  let history = useHistory();
  //获取url中的参数
  const params = useParams();
  const changeNavId = params.id;
  const [form] = Form.useForm();
  //获取某一条商品大类数据
  async function getNavInfo(_id) {
    const data = await navsApi.getOne(_id);
    form.setFieldsValue({
      name: data.name,
    });
  }
  //进入页面直接执行一次，获取优惠券的数据
  useEffect(() => {
    getNavInfo(changeNavId);
  });

  // 修改按钮的事件
  const onFinish = async (newNav) => {
    newNav._id = changeNavId;
    await navsApi.changeOne(newNav);
    message.success({
      content: "修改商品大类信息成功，即将跳转至商品大类列表",
      duration: 1,
      onClose: () => {
        history.push("/info/navs");
      },
    });
  };
  //取消修改的事件
  const cancelChange = () => {
    history.push("/info/navs");
  };
  return (
    <div className="site-card-border-less-wrapper">
      <Space direction="vertical" style={{ width: "100%" }}>
        <Card>
          <Breadcrumb>
            <Breadcrumb.Item>主页</Breadcrumb.Item>
            <Breadcrumb.Item>商品分类</Breadcrumb.Item>
            <Breadcrumb.Item>
              <a href="#/info/navs">商品大类列表</a>
            </Breadcrumb.Item>
            <Breadcrumb.Item>修改商品大类</Breadcrumb.Item>
          </Breadcrumb>
        </Card>
        <Card style={{ height: "640px" }}>
          <Form
            {...layout}
            name="complex-form"
            onFinish={onFinish}
            validateMessages={validateMessages}
            style={{ marginTop: "100px" }}
            form={form}
          >
            <Form.Item
              name="name"
              label="商品大类名称"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input
                placeholder="请输入商品大类名称"
                style={{ width: "300px" }}
              />
            </Form.Item>
            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 10 }}>
              <Button
                type="primary"
                htmlType="submit"
                style={{ marginRight: "10px" }}
              >
                保存修改
              </Button>
              <Button type="primary" onClick={cancelChange} danger>
                取消修改
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Space>
    </div>
  );
};
